-- UIOldAnvil
-- Created by huanghr May/24/2016
-- 老旧的铁砧

-- UIOldAnvil 继承自Layer
UIOldAnvil = class("UIOldAnvil", function()
    return cc.Layer:create();
end);

function UIOldAnvil.create(gridData)
    return UIOldAnvil.new(gridData);
end

-- 内部函数声明
local resize;
local MAX_SUBMIT_NUM = 2;

-- 构造函数
function UIOldAnvil:ctor(gridData)
    self:setName("UIOldAnvil");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/dungeon/special/DarkDragonStatue.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    self.gridData = gridData;
    self.submited = {};

    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    resize(node);
end

-- 适配
function resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册事件处理回调函数
function UIOldAnvil:registerEventCallback()
    -- 关注工坊放入装备的事件
    EventMgr.register("UIOldAnvil", event.BLACKSMITH_INPUT_EQUIP, function(args)
        self:whenInputEquip(args);
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UIOldAnvil", event.FORGE_SPADE_SUCC, function(args)
        self:forgeSucc(args);
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIOldAnvil 界面析构清理");
            EventMgr.removeAll("UIOldAnvil");

            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():showMenu();
                UIDungeonMgr:getCurLevel():showTop();
            end
        elseif eventType == "enter" then
            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():hideMenu();
                UIDungeonMgr:getCurLevel():hideTop();
            end
        end
    end);
end

-- 注册点击事件
function UIOldAnvil:registerTouchEvent()
    local node = self.node;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");

            -- 先把选择框中脱下来的装备穿上去
            for index = 1, MAX_SUBMIT_NUM do
                local info = self.submited[index] or {};
                local classId = info.class_id;
                local isUnequiped = info.isUnequiped;

                if type(classId) == "number" and isUnequiped then
                    DungeonActionM.go("do_equip", 0, classId);
                end
            end

            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIOldAnvil");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);

    -- 注册确定按钮点击事件
    local btnOk = findChildByName(node, "CT/btn_ok");
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_confirm");
            -- 判断是否放入装备
            -- 取出所有提交的装备的class_id
            local submitList = {};

            for index = 1, MAX_SUBMIT_NUM do
                local info = self.submited[index] or {};
                if type(info.class_id) == "number" then
                    table.insert(submitList, info.class_id);
                end
            end

            -- 判断是否放入装备
            if #submitList < 2 then
                alert(getLocStr("forge_spade_material_lock"));
                return;
            end

            local effectNode1 = findChildByName(self.node, "CT/effect_node1");
            local effectNode2 = findChildByName(self.node, "CT/effect_node2");

            local callFunc1 = cc.CallFunc:create(function()
                -- playEffect(effectNode1, 1264, -18, 190, nil, 1.3);
                -- playEffect(effectNode2, 1263, -20, 180, nil, 1.3);

            end);

            local delay = cc.DelayTime:create(0.4);
            local callFunc2 = cc.CallFunc:create(function()
                -- playEffect(effectNode1, 1264, -18, 190, nil, 1.3);
                -- playEffect(effectNode2, 1263, -20, 180, nil, 1.3);
                playEffect(effectNode2, 1151, 0, 80);
                btnOk:setTouchEnabled(false);
            end);

            local delay2 = cc.DelayTime:create(1);
            local callFunc3 = cc.CallFunc:create(function()
                -- 调用回调处理
                DungeonActionM.go("forge_spade", self.gridData:getPos(),
                    bit.blshift(submitList[1], 16) + submitList[2]);
            end);

            self.node:runAction(cc.Sequence:create(callFunc2, delay2, callFunc3));
        end
    end

    btnOk:addTouchEventListener(onOkClick);

    -- 注册装备点击格点击事件，固定2个
    for index = 1, MAX_SUBMIT_NUM do
        local equipGrid = findChildByName(node, string.format("CT/submit_node%d/frame", index));
        local function onEquipClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_click");
                -- 可提交的装备列表（铁块，木材）
                local submitList = self.gridData.cost;

                -- 打开装备选择界面
                -- 传入参数：通过魔神雕像方式打开
                local uiEquip = UIEquips.create(EQUIP_OPEN_TYPE_DARK_DRAGON, {["index"] = index, ["submited"] = { submitList[index], },});
                UIMgr.getCurrentScene():addForm(uiEquip);
            end
        end
        equipGrid:addTouchEventListener(onEquipClick);
    end
end

-- 重绘
function UIOldAnvil:redraw()
    local CT = findChildByName(self.node, "CT");
    local BT = findChildByName(self.node, "BT");

    -- 玩家当前的信息
    local class = self.gridData.classify;

    -- 显示标题
    local buildingInfo = BuildingBonusM.queryBuildingView(self.gridData.class);
    local title = buildingInfo["title"]
    local titleLabel = findChildByName(CT, "title_node/title");
    TextStyleM.setTextStyle(titleLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_CYAN, true);
    titleLabel:setString(title)
    TextStyleM.setArtWordTitleStyle(titleLabel);

    -- 显示功能描述
    local desc = buildingInfo["dialog"];
    local descLabel = findChildByName(CT, "desc_node/desc");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    applyString(descLabel, desc);

    -- 显示建筑图标
    local mainIcon = findChildByName(CT, "icon");
    local icon = BuildingBonusM.queryBuildingView(self.gridData.class, "icon");
    mainIcon:loadTexture(getLevelItemIconPath(icon));

    -- 提交框
    local submitImgs = {};
    for index = 1, MAX_SUBMIT_NUM do
        local equipGrid = findChildByName(CT, string.format("submit_node%d/item_icon", index));
        submitImgs[index] = equipGrid;
    end
    self.submitImgs = submitImgs;

    self:redrawEquip();

    local tipLabel = findChildByName(CT, "tip_node/text_tip");
    tipLabel:setVisible(false);

    -- 显示确定按钮
    local btnOk = findChildByName(CT, "btn_ok");
    local okText = buildingInfo["view_text"];
    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOk:setTitleText(okText);
    setButtonEnabled(btnOk, true);

    -- 显示返回按钮
    local btnBack = findChildByName(BT, "btn_back");
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 重绘装备格
function UIOldAnvil:redrawEquip()
    -- 取出所有提交的装备的class_id
    local submitList = {};

    for index = 1, MAX_SUBMIT_NUM do
        local info = self.submited[index] or {};
        if type(info.class_id) == "number" then
            table.insert(submitList, info.class_id);
        end
    end

    local suitInfo = filterSuit(submitList) or {};

    local submitConfig = self.gridData.cost;

    for index = 1, MAX_SUBMIT_NUM do
        local submited = self.submited or {};
        local frame = findChildByName(self.node, string.format("CT/submit_node%d/frame", index));

        if not submited[index] then
            self.submitImgs[index]:setVisible(false);

            self.submitImgs[index]:setVisible(true);
            local icon = ItemM.query(submitConfig[index], "icon");
            self.submitImgs[index]:loadTexture(getItemIconPath(icon));

            self.submitImgs[index]:setOpacity(80);

            if ItemM.getOwnedAmount(ME.user, submitConfig[index]) > 0 then
                -- 可穿戴，播放动画
                playBubbleAnima2(self.submitImgs[index], false);
            end
        else
            self.submitImgs[index]:setVisible(true);
            local icon = ItemM.query(submited[index].class_id, "icon");
            self.submitImgs[index]:loadTexture(getItemIconPath(icon));

            self.submitImgs[index]:setOpacity(255);

            self.submitImgs[index]:stopAllActions();
            self.submitImgs[index]:removeAllChildren();

            frame:removeAllChildren();
        end

        if table.indexOf(table.keys(suitInfo), index) > 0 then
            self.submitImgs[index]:stopAllActions();
            self.submitImgs[index]:removeAllChildren();

            frame:removeAllChildren();
            playEffect(self.submitImgs[index], 1265, 50, 50, nil, 1.2);
        end
    end
end

-- 工坊放入装备的回调
function UIOldAnvil:whenInputEquip(args)
    local equipId = args.classId;
    local isEquiped = args.isEquiped;
    local index = args.index;
    if not equipId or not index then
        return;
    end

    -- 记录装备id
    local submited = self.submited or {};
    local lastEquip = submited[index] or {};
    submited[index] = { ["class_id"] = equipId, ["isUnequiped"] = isEquiped, };
    self.submited = submited;

    -- 如果之前这个格子放了脱下来的装备，那么要穿回去
    if lastEquip.isUnequiped then
        DungeonActionM.go("do_equip", 0, lastEquip.class_id);
    end

    -- 重绘装备格
    self:redraw();
end

-- 雕像献祭的回调
function UIOldAnvil:forgeSucc(args)
    self.submited = {};
     -- 刷新下
    self:redraw();

    -- 关闭当前界面
    UIMgr.getCurrentScene():removeFormByName("UIOldAnvil");

    alert(getLocStr("forge_spade_succ"));
end
